package com.mj.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import com.androidquery.AQuery;
import com.mj.R;
import com.mj.activity.Activity_Detail;
import com.mj.bean.Avatar;
import com.mj.util.DensityUtil;

public class JuyouAdapter extends ArrayAdapter<Avatar> {
	private int width;

	public JuyouAdapter(Context context, ArrayList<Avatar> arrayList) {
		super(context, 0, arrayList);
		int margin = DensityUtil.dip2px(context, 6 * 4);
		width = (DensityUtil.getDisplay(context).widthPixels - margin) / 3;
	}

	@Override
	public int getCount() {
		int count = super.getCount() / 3;
		return super.getCount() % 3 == 0 ? count : count + 1;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.item_juyou, null);
		}
		AQuery aq = new AQuery(convertView);
		Avatar avatar1 = getItem(position * 3);
		aq.id(R.id.imageView1).clicked(new imageClick(avatar1)).width(width, false).height(width, false).image(avatar1.getAvatar());
		aq.id(R.id.textView1).text(avatar1.getDistance() + "米");
		if (position * 3 + 1 < super.getCount()) {
			Avatar avatar2 = getItem(position * 3 + 1);
			aq.id(R.id.imageView2).clicked(new imageClick(avatar2)).visible().width(width, false).height(width, false)
					.image(avatar2.getAvatar());
			aq.id(R.id.textView2).visible().text(avatar2.getDistance() + "米");
		} else {
			aq.id(R.id.imageView2).clicked(null).gone();
			aq.id(R.id.textView2).gone();
		}
		if (position * 3 + 2 < super.getCount()) {
			Avatar avatar3 = getItem(position * 3 + 2);
			aq.id(R.id.imageView3).clicked(new imageClick(avatar3)).visible().width(width, false).height(width, false)
					.image(avatar3.getAvatar());
			aq.id(R.id.textView3).visible().text(avatar3.getDistance() + "米");
		} else {
			aq.id(R.id.imageView3).clicked(null).gone();
			aq.id(R.id.textView3).gone();
		}
		return convertView;
	}

	class imageClick implements OnClickListener {
		private Avatar avatar;

		public imageClick(Avatar avatar) {
			this.avatar = avatar;
		}

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(getContext(), Activity_Detail.class);
			intent.putExtra("avatar", avatar);
			getContext().startActivity(intent);
		}
	}
}
